var CustomMailDisplay = Class.create();
CustomMailDisplay.prototype = {
    initialize: function(){
        this.useflag = 1;
        this.rootNode = null;
        this.rootName = '';
        this.customDays = [];
        this.imgindex = 0;
        this.imgList = [];
        // this.containFes = 0;
        this.subjectflag = 0;
        this.typeflag = 0;
        this.subjects = ['送你养生小妙招', '亲爱的，请接受我绵绵的祝福', '朋友，我对你的祝福不间断', '衷心祝你生活如意、工作顺心！'];
		// 记录用户是否使用了地址簿
		// this.addressbook_use_flag = 0;
    },
    // fix selectedIndex bug (根据selectedIndex选择，改为根据option value选择)
    selectedValue: function(sobj) {
        var _S = sobj;
        return _S.getElementsByTagName('option')[_S.selectedIndex].value;
    },
    loadConfigPanel: function(){
        custom_mail_list({}, this.listSuccessFromPanelCallBack.bind(this), this.listFailCallBack.bind(this));
    },
    listSuccessFromPanelCallBack: function(ret){
        if (ret.result != 0) {
			DOM.mailConfiguration.innerHTML = CustomMailAltNewTemplete;
        } else {
            hiddenAllPanel();
            DOM.mailConfiguration.show();
            this.initPageWithData(ret.data);
        }
    },
	
    //提交信息，定制传情计划
    submitMail: function(){
        if (this.useflag == 0) {
            _dialog.alert({
                info: '请选择定制的频率'
            });
            return false;
        } else {
            var params = {};
            var sendIndex = this.collectDays();
            if (sendIndex < 0) {
                _dialog.alert({
                    info: '请定制日期'
                });
                return false;
            }
            if (this.customDays.length == 0) {
                _dialog.alert({
                    info: '请定制日期'
                });
                return false;
            }
            params['sendIndex'] = sendIndex;
			
			var emails = writemail.getSendEmail2ArrayList($('compose.wto').value);
			if(emails.length > 20) {
				_dialog.alert({info: '最多只能有20个收件人地址'});
				return false;
			}
			// 生成反垃圾邮件的验证码
			try {
				mail_send_e.genuuid();
			} catch(e) {}
			params.securityCode = mail_send_e.UUID;
        	params.sendtime = mail_send_e._sendtime;
            // var _s = $('subject_selector');
            // params[ 'subject' ] = this.subjectflag == 0 ? this.subjects[this.selectedValue($('subject_selector'))] : $( 'custom_subject' ).value;
            // params['subject'] = this.subjectflag == 0 ? _s[_s.selectedIndex].innerHTML : $('custom_subject').value;
			params['subject'] = $('compose.subject').value;
            params['cc_myself'] = $('cc_myself').checked ? 1 : 0;
            // params['tid'] = Object.toJSON(emails);
			params['tid'] = emails.join(',');
            params['freq'] = $('freq_selector').selectedIndex;
            params['type'] = this.typeflag;
            // params['isFre'] = $('containFes').checked == true ? 1 : 0;
			params['isFre'] = 0;
            //针对免费邮箱
            params['uid'] = UserSohuID;
            //针对VIP邮箱
            //如果mt为2，那么就是免费版本
            //如果mt为1，那么就是vip版本
            params['mt'] = 2;
            params['addressbook_use_flag'] = writemail.addressbook_use_flag;
			params['addressbook_use_list'] = writemail.addressbook_use_list;
            params['days'] = Object.toJSON(this.customDays);
            custom_mail_save(params, this.saveSuccessCallBack.bind(this), this.saveFailCallBack.bind(this));
        }
    },
    saveSuccessCallBack: function(r){
        this.customMailCache = null;
        if (r.result == 0) {
            _dialog.alert({
                info: '设置成功'
            });
            hiddenAllPanel();
            $('mailConfiguration').style.display = '';
            custom_mail_display.loadConfigPanel();
        }
        else {
            var msg = '';
            switch (r.result) {
                case -1:
                    msg = "设置的日期数量不合法";
                    break;
                case -2:
                    msg = "设置的收件人数量超过了18个";
                    break;
                case -3:
                    msg = "设置失败，请稍后重试";
                    break;
                case -4:
                    msg = "没有选择时间";
                    break;
                default:
                    msg = "未知错误";
                    break;
            }
            // alert( msg );
            _dialog.alert({
                info: msg
            });
        }
    },
    saveFailCallBack: function(){
        var q = 123;
    },
    collectDays: function(){
        if (this.useflag == 1) {
            this.weekchange();
            return $('week_selector').selectedIndex;
        }
        else 
            if (this.useflag == 2) {
                this.monthchange();
                return $('month_selector').selectedIndex;
            }
            else {
                return -1;
            }
    },
	
    freqchange: function(){
        var index = $('freq_selector').selectedIndex;
        switch (index) {
            case 0:
                this.disWeek();
                break;
            case 1:
                this.disMonth();
                break;
            default:
                this.hiddenAllSelector();
                break;
        }
    },
    disWeek: function(){
        this.hiddenAllSelector();
        this.useflag = 1;
        if ($('week_selector')) {
            $('week_selector').style.display = '';
            $('week_selector').observe('change', this.weekchange.bind(this));
            this.collectDays();
            return;
        }
    },
    disMonth: function(){
        this.hiddenAllSelector();
        this.useflag = 2;
        if ($('month_selector')) {
            $('month_selector').style.display = '';
            this.collectDays();
            return;
        }
        var dis = "<select id='month_selector'>";
        for (var i = 1; i <= 31; i++) {
            dis += "<option>" + i + "</option>";
        }
        dis += "</select>";
        new Insertion.After('week_selector', dis);
        $('month_selector').observe('change', this.monthchange.bind(this));
        this.collectDays();
    },
    monthchange: function(){
        this.useflag = 2;
        this.customDays = [];
        var index = $('month_selector').selectedIndex;
        index++;
        var date_now = new Date();
        var monthindex_now = date_now.getDate();
        var sub_index = index - monthindex_now;
        var res = custom_mail.dateAdd(date_now, "d", sub_index);
        this.customDays = custom_mail.collectMonths(res);
    },
    weekchange: function(){
        this.useflag = 1;
        this.customDays = [];
        var index = $('week_selector').selectedIndex;
        if (index == 0) {
            return;
        }
        var date_now = new Date();
        var weekindex_now = date_now.getDay();
        //周日的，特殊处理下
        //周日的特殊源自于javascript默认将周日作为一周的开始，而我们常规的思想则是周日作为一周的结束，所以，此处，如果判断到是周日了，那么需要将周日前推一个周，再进行下边的运算，才能符合常规。
        //So hack it
        var sub_index = 0;
        sub_index = (index == 1) ? (0 - weekindex_now) : index - weekindex_now - 1;
        var res = custom_mail.dateAdd(date_now, "d", sub_index);
        this.customDays = custom_mail.collectDays(res).clone();
    },
	
    updatePreviewPrompt: function(index){
		var _index = index ? index : 1;
		$('customShowArea').src = MailConst.STATIONERY + '/../convey/convey_' + _index + '.jpg';
		this.typeflag = (_index - 1);
    },
    hiddenAllSelector: function(){
        this.customDays = [];
        this.useflag = 0;
        try {
            $('week_selector').style.display = 'none';
        } 
        catch (e) {
        }
        try {
            $('month_selector').style.display = 'none';
        } 
        catch (e) {
        }
    },
	
	// 界面的入口函数
    initConfPage: function(rsh) {
        try {
            if (this.customMailCache) {
                this.listSuccessCallBack(rsh, this.customMailCache);
            } else {
                custom_mail_list({}, this.listSuccessCallBack.bind(this, rsh), this.listFailCallBack.bind(this));
            }
        } catch (e) { }
        try {
            deleteLoadPage();
        } catch (e) { }
    },
    initNewPage: function(){
        changeToolbarStyle('customMail');
        changePanel('userMail');
        return false;
    },
    listSuccessCallBack: function(rsh, ret){
        this.customMailCache = ret;
		try {
			if(!DOM.composeMail.visible()) {
				hiddenAllPanel();
				// changePanel('composeMail');
				DOM.composeMail.show();
				appendAddressBook()
			}
		} catch(e) {}
		try {
			writemail.writeFunc.each(function(item, index) {
				var _item = $(item);
				if(index == 2) {
					try {
						_item.show();
						_item.style.visibility = 'visible';
					} catch(e) {}
				} else {
					try {
						_item.hide();
						_item.style.visibility = 'hidden';
					} catch(e) {}
				}
			});
		} catch(e) {}
		$('convey_area').innerHTML = CustomMailNewTemplete;
		var _fname = (function() {
			try {
				return mailCfgClass.getProfileContent().fullname + '';
			} catch(e) {
				return SUID;
			}
		})();
		$('compose.subject').value = ((typeof _fname != 'undefined' && _fname != 'undefined' && _fname && !_fname.blank()) ? _fname : SUID) + ' 为你制作的传情贺卡';
		// 初始化默认的传情图片
        this.updatePreviewPrompt(3);
		try {
			Element.hide(DOM.compose_wto.nextSibling);
			Element.hide(DOM.compose_wto.nextSibling.nextSibling);
			Element.hide(DOM.compose_wto.nextSibling.nextSibling.nextSibling);
            write_mail_single_flag = 0;
            DOM.compose_wto.previousSibling.innerHTML = '收件人：';
		} catch(e) {}
		
        if (ret.result != 0) {
			try {
				if(!DOM.top_operate_area) DOM.top_operate_area = $('top_operate_area');
				if(!DOM.bottom_operate_area) DOM.bottom_operate_area = $('bottom_operate_area');
				DOM.top_operate_area.innerHTML = convey_top_html;
				DOM.bottom_operate_area.innerHTML = convey_bottom_html;
			} catch(e) {}
			
			$('select_convey_operate').innerHTML = conveyBookHTML();
			
            $('week_selector').observe('change', this.weekchange.bind(this));
            $('freq_selector').observe('change', this.freqchange.bind(this));
            
			// 初始化这张图片默认选中
			try {
				var _csa = $('convey_scroll_area');
				Element.addClassName(_csa.childNodes[2], 'letter-focus');
				writemail.focusLetterEL = _csa.childNodes[2];
			} catch(e) {}
        } else {
			try {
				if(!DOM.top_operate_area) DOM.top_operate_area = $('top_operate_area');
				if(!DOM.bottom_operate_area) DOM.bottom_operate_area = $('bottom_operate_area');
				DOM.top_operate_area.innerHTML = convey_top_disable_html;
				DOM.bottom_operate_area.innerHTML = convey_bottom_disable_html;
			} catch(e) {}
			$('select_convey_operate').innerHTML = conveyDisabledBookHTML(ret.data);
        }
		var _sco = $('select_convey_operate');
		_sco.hide();
		if(!this.scrollAnimation) this.scrollAnimation = new ScrollAnimation('convey_scroll_area');
		this.scrollAnimation.slideDown(_sco, 70);
		addAjaxHistory('userMail', 'changePanel("userMail", null, true);', '传情计划', rsh);
    },
    initPageWithData: function(ret){
        var obj = ret.evalJSON();
        var t = new Template(CustomMailListTemplete);
        var data = {};
        if (obj.isCC == 1) {
            data["str_ccself"] = "抄送给自己";
        }
        else {
            data["str_ccself"] = "无";
        }
        switch (obj.typeid) {
            case 0:
                data["str_type"] = "日常问候";
                break;
            case 1:
                data["str_type"] = "商务问候";
                break;
            case 2:
                data["str_type"] = "魔法情书";
                break;
            case 3:
                data["str_type"] = "健康养生";
                break;
            default:
                data["str_type"] = "健康养生";
                break;
        }
        var fesdays = '';
        var days = obj.mailday.split("|");
        days = days.sort().compact();
        var start = end = '';
        var start_flag = 0;
        days.each(function(d){
            if (d != "" && start_flag == 0) {
                start = d;
                start_flag = 1;
            }
        });
        end = days[days.length - 1];
        var freq_list = "";
        if (obj.isFre == 1 && days.length > 0) {
            days.each(function(d){
                var nofestflag = 0;
                if (d != "") 
                    try {
                        var ty = ("" + d).substr(0, 4);
                        var tm = ("" + d).substr(4, 2);
                        var td = ("" + d).substr(6, 2);
                        tm = parseInt(tm);
                        td = parseInt(td);
                        //先进行阳历（洋历？）的判断
                        switch (tm) {
                            case 1:{
                                if (td == 1) {
                                    //元旦，古典节日中并没有这一天
                                    fesdays += "元旦节 ";
                                }
                            };
							break;
                            case 10:{
                                if (td == 1) {
                                    //国庆节，古典节日中也没有这样的一天
                                    fesdays += "国庆节 ";
                                }
                            };
							break;
                            case 12:{
                                if (td == 25) {
                                    //圣诞节，唉，基督教的节日也要过的么？什么世道啊，我不信教。
                                    fesdays += "圣诞节 ";
                                }
                            };
						break;
                        };
                        var flag = new Date(ty, tm - 1, td);
                        var q = new Lunar(flag);
                        var res = custom_mail.isLurFesDays(q);
                        switch (res) {
                            case 6:{
                                if (freq_list.indexOf("2") < 0) {
                                    fesdays += "端午节 ";
                                    freq_list += "2";
                                }
                            };
							break;
                            case 7:{
                                if (freq_list.indexOf("3") < 0) {
                                    fesdays += "中秋节 ";
                                    freq_list += "3";
                                }
                            };
							break;
                            case 5:{
                                if (freq_list.indexOf("1") < 0) {
                                    fesdays += "春节 ";
                                    freq_list += "1";
                                }
                            };
							break;
                        };
                    }
                    catch (e) { }
            });
        }
        if (fesdays == "") {
            fesdays = "无";
        }
        data["str_festival"] = fesdays;
        data["str_subject"] = obj.subject;
        if (obj.freq == 0) {
            data["str_freq"] = "每星期一次（共" + (days.length - 1) + " 封邮件）";
        }
        else 
            if (obj.freq == 1) {
                data["str_freq"] = "每月一次（共" + (days.length - 1) + " 封邮件）";
            }
            else {
                data["str_freq"] = "Hey, 我这刻就震惊了，你是怎么做到的？";
            }
        str_receivers = '';
        tids = obj.tid.split(",");
        var flag_receiver = 0;
        if (tids.length > 5) {
            for (var i = 0; i < tids.length; i++) {
                if (flag_receiver == 5 && tids[i] != "") {
                    str_receivers += "</dd><dd>";
                    str_receivers += tids[i] + ",";
                    flag_receiver = 0;
                }
                else {
                    if (tids[i] != "") {
                        str_receivers += tids[i] + ",";
                        flag_receiver++;
                    }
                }
            }
            
            data["str_receivers"] = str_receivers;
        }
        else {
            data["str_receivers"] = obj.tid;
        }
        $('mailConfiguration').update(t.evaluate(data));
    },
    deleteNow: function(){
        var confunc = function(){
            var param = {
                pass: 'sohu'
            };
            custom_mail_delete(param, this.deleteSuccess.bind(this), this.listFailCallBack.bind(this));
        }.bind(this);
        _dialog.confirm({
            info: '删除此计划，未执行的计划邮件将不再被发送',
            click: function(){
                confunc();
            }
        });
        return;
        
    },
    deleteSuccess: function(ret){
        this.customMailCache = null;
        if (ret.result == 0) {
            _dialog.alert({
                info: '删除成功'
            });
            changePanel("mainPage");
        }
        else {
            _dialog.alert({
                info: '系统错误，请稍后重试！'
            });
        }
    },
    listFailCallBack: function(){
        _dialog.alert({
            info: '系统错误，请稍后重试！'
        });
    },
    exit: function(){
    }
};

var custom_mail_display = new CustomMailDisplay();



